package com.javaweb.controller;

import com.javaweb.entity.Result;
import com.javaweb.entity.User;
import com.javaweb.service.UserService;
import com.javaweb.utils.JwtUtil;
import com.javaweb.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    //用户名和密码必须是5~16位非空字符
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        log.info("用户注册。用户名：{}，密码：{}", username, password);

        //查询用户
        User user = userService.findByUsername(username);
        if (user == null) {
            userService.register(username, password);
            log.info("注册成功。用户名：{}，密码：{}", username, password);
            return Result.success();
        } else {
            log.info("注册失败。用户名已被注册");
            return Result.error("用户名已被注册");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        log.info("用户登录。用户名：{}，密码：{}", username, password);

        //查询用户
        User user = userService.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());

            String token = JwtUtil.generateToken(claims); //包含了当前员工的登录信息

            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, JwtUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS); //2小时后令牌被删除

            log.info("登陆成功。用户名：{}，密码：{}", username, password);
            return Result.success(token);
        }

        log.info("登陆失败。用户名或密码错误");
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/info")
    public Result userInfo() {
        //根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();

        String username = String.valueOf(map.get("username"));

        log.info("查询用户信息。用户名：{}", username);

        User user = userService.findByUsername(username);

        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {

        log.info("更新用户信息。用户：{}", user);

        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {

        log.info("更新用户头像url。url：{}", avatarUrl);

        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {

        log.info("更新用户密码-1。参数：{}", params);

        //校验参数
        //原密码
        String oldPwd = params.get("oldPwd");
        //新密码
        String newPwd = params.get("newPwd");
        //重复新密码
        String rePwd = params.get("rePwd");

        if (!StringUtils.hasLength(oldPwd) ||
                !StringUtils.hasLength(newPwd) ||
                !StringUtils.hasLength(rePwd)) {
            log.info("更新失败。缺少必要参数");
            return Result.error("缺少必要参数");
        }

        //根据用户名拿到原密码
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = String.valueOf(map.get("username"));

        log.info("更新用户密码-2。用户名：{}，原密码：{}，新密码：{}", username, oldPwd, newPwd);

        User user = userService.findByUsername(username);

        if (!user.getPassword().equals(oldPwd)){
            log.info("更新失败。原密码错误");
            return Result.error("原密码错误");
        }

        if (!newPwd.equals(rePwd)){
            log.info("更新失败。两次填写的新密码不一致");
            return Result.error("两次填写的新密码不一致");
        }

        //调用service完成密码更新
        userService.updatePwd(newPwd);

        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        log.info("更新成功。用户名：{}，新密码：{}", username, newPwd);
        return Result.success();
    }
}
